package com.buaa.springboot.fileupload.controller;

import com.buaa.springboot.fileupload.entity.ResponseMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Comparator;


@RestController
@CrossOrigin
public class UploadController {
    @Value("${file.path}")
    private String dirPath;

    @PostMapping("/chunk")
    public ResponseMessage upLoadChunk(@RequestParam("chunk") MultipartFile chunk,
                                       @RequestParam("filename") String filename) {
        File folder = new File(dirPath);
        if (!folder.exists() && !folder.isDirectory())
            folder.mkdirs();
        String filePath = dirPath + File.separator + filename;

        try {
            File saveFile = new File(filePath);
            FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
            fileOutputStream.write(chunk.getBytes());
            fileOutputStream.close();
            chunk.transferTo(saveFile);
            System.out.println(filename);
            return ResponseMessage.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseMessage.ok();
    }

    @GetMapping("/merge")
    public ResponseMessage MergeChunk(@RequestParam("hash") String hash,
                                      @RequestParam("filename") String filename) {
        File chunkFileFolder = new File(dirPath);
        File mergeFile = new File(dirPath + File.separator + filename);
        File[] chunks = chunkFileFolder.listFiles();
        //排序
        assert chunks != null;
        File[] files = Arrays.stream(chunks)
                .filter(file -> file.getName().startsWith(hash))
                .sorted(Comparator.comparing(o -> Integer.valueOf(o.getName().split("\\.")[0].split("_")[1])))
                .toArray(File[]::new);

        try {
            RandomAccessFile randomAccessFileWriter = new RandomAccessFile(mergeFile, "rw");
            byte[] bytes = new byte[1024];
            for (File chunk : files) {
                RandomAccessFile randomAccessFileReader = new RandomAccessFile(chunk, "r");
                int len;
                while ((len = randomAccessFileReader.read(bytes)) != -1) {
                    randomAccessFileWriter.write(bytes, 0, len);
                }
                randomAccessFileReader.close();
            }
            randomAccessFileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(hash);
        return ResponseMessage.ok(mergeFile);
    }
}
